package weibo4j.publicapi;

import java.util.ArrayList;
import java.util.List;

import weibo4j.Weibo;
import weibo4j.model.PostParameter;
import weibo4j.model.ShortUrl;
import weibo4j.model.ShortUrlWapper;
import weibo4j.model.Status;
import weibo4j.model.WeiboException;
import weibo4j.util.WeiboConfig;

/**
 * 
 * @author Administrator
 * 短链接工具，不需要验证
 */
public class ShortUrlUtil{
	
	/**
	 * @ 长链接变短链接
	 * @param url_short 短链接
	 * @return 
	 * @throws WeiboException
	 */
	public static ShortUrlWapper expand(String url_short) throws WeiboException{
		return ShortUrl.ShortUrlWapper(Weibo.client.get(
					WeiboConfig.getValue("baseURL")+"short_url/expand.json",new  PostParameter[]{
						new PostParameter("url_short",url_short)
					}
				));
	}
	
	public static ShortUrlWapper expand(List<String> listUrl) throws WeiboException{
		PostParameter[] paramArray = new PostParameter[listUrl.size()];
		if(!listUrl.isEmpty()){
			List<PostParameter> pList = new ArrayList<PostParameter>();
			for(String s: listUrl){
				pList.add(new PostParameter("url_short",s));
			}
			return ShortUrl.ShortUrlWapper(Weibo.client.get(WeiboConfig.getValue("baseURL")+"short_url/expand.json",(PostParameter[])pList.toArray()));
					
		}else{
			return null;
		}
	}
	
	/**
	 * 将s中的短链接挑选出来
	 * @param s 字符串
	 * @return 短链接列表
	 */
	public static List<String> shortStr(String s){
		List<String> listStr = new ArrayList<String>();
		String begin = "http://t.cn/";
		int offest = begin.length();			//偏移量
		int linkBegin = -1;                     //链接开始处
		for(int i = 0; i < s.length(); i++){
			linkBegin = s.indexOf(begin,i);
			if(linkBegin < 0){
				break;
			}
			for(int j = linkBegin+offest; j < s.length(); j++){
				i = j;
				char t = s.charAt(j);
				if(!(Character.isDigit(t)) &&(!Character.isLetter(t))){
					break;
				}
				
			}
		
			String link = s.substring(linkBegin,i);
		
			
			listStr.add(link);
			
		}
		return listStr;
	}
	
	public static String filterUrl(String s){
		
		String source = "";
		String begin = "http://t.cn/";
		int offest = begin.length();			//偏移量
		int linkBegin = -1;                     //链接开始处
		int lastEnd   = 0;
		for(int i = 0; i < s.length(); i++){
			linkBegin = s.indexOf(begin,i);
			if(linkBegin < 0){
				source += s.substring(lastEnd,s.length());
				break;
			}
			for(int j = linkBegin+offest; j < s.length(); j++){
				i = j;
				char t = s.charAt(j);
				if(!(Character.isDigit(t)) &&(!Character.isLetter(t))){
					break;
				}
				
			}
			source += s.substring(lastEnd,linkBegin);
			lastEnd = i;
		
		}
		return source;
	}
	
}
